<template>
  <div class="detect-container">
    <!-- 限时免费通知条 -->
    <div class="promo-banner">
      <el-icon><Promotion /></el-icon>
      <span class="promo-text">限时活动：每天五次<span class="highlight-text">免费</span>查重</span>
    </div>

    <div class="detect-content-wrapper">
      <el-card class="detect-card">
        <div class="detect-header">
          <h2><el-icon><Search /></el-icon> 论文查重系统</h2>
          <p class="subtitle">专业高效的学术文本查重工具</p>
        </div>

        <el-divider content-position="center">选择检测方式</el-divider>

        <el-tabs v-model="activeTab" class="detect-tabs">
          <el-tab-pane name="file" label="文件上传">
            <div class="upload-area">
              <el-upload
                  class="upload-box"
                  drag
                  action="/api/upload"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :file-list="fileList"
              >
                <el-icon class="upload-icon"><UploadFilled /></el-icon>
                <div class="upload-text">拖拽文件到此处或 <em>点击上传</em></div>
                <div class="upload-tip">支持DOCX格式，最大15MB，<span class="word-count-requirement">字数须大于4000字</span></div>
              </el-upload>

              <div v-if="fileList.length" class="uploaded-files">
                <div class="file-item">
                  <el-icon><Document /></el-icon>
                  <span class="file-name">{{ fileList[0].name }}</span>
                  <span class="file-word-count">{{ fileWordCount }}字</span>
                  <el-icon @click="removeFile"><Delete /></el-icon>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane name="text" label="文本输入">
            <el-input
                v-model="inputText"
                type="textarea"
                :rows="8"
                placeholder="请输入需要查重的文本内容(字数须大于2000字)"
                class="text-input"
            />
            <div class="text-counter" :class="{'text-counter-error': inputText.length > 0 && inputText.length < 2000}">
              当前字数: {{ inputText.length }}
              <span v-if="inputText.length > 0 && inputText.length < 2000">
                (字数不足，至少需要2000字)
              </span>
            </div>
          </el-tab-pane>
        </el-tabs>

        <div class="action-area">
          <el-button
              type="primary"
              class="submit-btn"
              :loading="isDetecting || isWaitingResult"
              :disabled="!canSubmit"
              @click="startDetection"
          >
            开始查重
          </el-button>
        </div>
      </el-card>

      <!-- 右侧查重图片 -->
      <div class="detect-image">
        <img src="/查重.png" alt="查重系统展示" />
      </div>
    </div>

    <!-- 查重进度展示 -->
    <el-dialog
        v-model="isDetecting"
        title="检测进行中"
        :show-close="false"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="500px"
        class="detect-dialog"
    >
      <div class="progress-content">
        <div class="progress-icon">
          <el-icon v-if="progress < 100" class="spinning"><Loading /></el-icon>
          <el-icon v-else><Clock /></el-icon>
        </div>
        <h3>{{ progress === 100 ? '正在生成报告...' : '正在检测文档相似度' }}</h3>
        <el-progress
            :percentage="progress"
            :stroke-width="20"
            striped
            :status="progress === 100 ? 'success' : ''"
            class="progress-bar"
        />
        <div class="progress-info">
          {{ progressStatusText }}
        </div>
      </div>
    </el-dialog>

    <!-- 结果展示 -->
    <el-dialog
        v-model="showResult"
        title="检测报告"
        width="500px"
        class="result-dialog"
    >
      <div class="result-content">
        <div class="result-header">
          <div class="similarity-display">
            <div :class="['similarity-circle', similarityLevelClass]">
              <span class="similarity-value">{{ similarity }}%</span>
            </div>
            <div class="similarity-text">
              <span class="similarity-label">相似度</span>
              <span :class="['similarity-level', similarityLevelClass]">{{ similarityLevelText }}</span>
            </div>
          </div>
        </div>

        <div class="result-details">
          <div class="detail-item">
            <span class="label">检测时间</span>
            <span class="value">{{ detectionTime }}</span>
          </div>
          <div class="detail-item">
            <span class="label">检测字数</span>
            <span class="value">{{ wordCount }} 字</span>
          </div>
        </div>

        <div class="result-actions">
          <el-button type="primary" @click="resetDetection">重新检测</el-button>
          <!--          <el-button type="success">-->
          <!--            <el-icon><Download /></el-icon> 下载报告-->
          <!--          </el-button>-->
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router' // 引入路由
import {
  Document,
  Delete,
  UploadFilled,
  Clock,
  Loading,
  Search,
  Download,
  Promotion
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import mammoth from 'mammoth'


// 获取路由实例 - 这一行是关键
const router = useRouter()
const userId = ref(sessionStorage.getItem('userId'))

// 检测模式选项卡
const activeTab = ref('file')

// 文件上传相关
const fileList = ref([])
const inputText = ref('')
const fileWordCount = ref(0)

// 检测状态
const isDetecting = ref(false)
const isWaitingResult = ref(false)
const progress = ref(0)
const progressTimer = ref(null)
const showResult = ref(false)

// 检测结果
const similarity = ref(0)
const detectionTime = ref('')
const wordCount = ref(0)

// 计算属性
const canSubmit = computed(() => {
  if (activeTab.value === 'file') {
    return fileList.value.length > 0
  } else {
    return inputText.value.trim().length > 0
  }
})

const similarityLevelClass = computed(() => {
  if (similarity.value < 20) {
    return 'level-low'
  } else if (similarity.value < 40) {
    return 'level-medium'
  } else {
    return 'level-high'
  }
})

const similarityLevelText = computed(() => {
  if (similarity.value < 30) {
    return '低度相似'
  } else if (similarity.value < 40) {
    return '中度相似'
  } else {
    return '高度相似'
  }
})

const progressStatusText = computed(() => {
  const texts = [
    '正在解析文档结构...',
    '正在分析文本内容...',
    '正在查询相似文献...',
    '正在比对相似度...',
    '正在生成检测报告...'
  ]

  if (progress.value < 20) {
    return texts[0]
  } else if (progress.value < 40) {
    return texts[1]
  } else if (progress.value < 70) {
    return texts[2]
  } else if (progress.value < 90) {
    return texts[3]
  } else {
    return texts[4]
  }
})

// 方法
const beforeUpload = async (file) => {
  const isDocx = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  const isLt15M = file.size / 1024 / 1024 < 15

  if (!isDocx) {
    ElMessage.error('仅支持DOCX格式文件')
    return false
  }

  if (!isLt15M) {
    ElMessage.error('文件大小不能超过15MB')
    return false
  }

  // 检查文档字数
  try {
    const arrayBuffer = await file.arrayBuffer()
    const result = await mammoth.extractRawText({ arrayBuffer })
    const text = result.value
    const count = text.length

    if (count < 4000) {
      ElMessage.error('文档字数不足4000字，请上传更多内容')
      return false
    }

    // 保存字数供后续显示
    fileWordCount.value = count
    fileList.value = [file]
    return false // 阻止自动上传
  } catch (error) {
    ElMessage.error('文档解析失败，请检查文件格式')
    return false
  }
}

const removeFile = () => {
  fileList.value = []
  fileWordCount.value = 0
}

// 文本输入框的字数校验
const validateInputText = () => {
  if (inputText.value.length < 2000) {
    ElMessage.warning('文本字数不足2000字，请输入更多内容')
    return false
  }
  return true
}

const startDetection = () => {
  if (!canSubmit.value) {
    if (activeTab.value === 'file') {
      ElMessage.warning('请先上传文件')
    } else {
      ElMessage.warning('请输入文本内容')
    }
    return
  }

  // 首先检查登录状态
  if (!userId.value) {
    ElMessage.warning('请先登录后再进行查重')
    router.push('/login') // 跳转到登录页面
    return
  }

  // 如果是文本输入方式，进行字数校验
  if (activeTab.value === 'text' && !validateInputText()) {
    return
  }

  // 开始检测
  isDetecting.value = true
  progress.value = 0

  // 将字数计算保存到检测结果中
  if (activeTab.value === 'file') {
    wordCount.value = fileWordCount.value
  } else {
    wordCount.value = inputText.value.length
  }

  // 模拟进度条，速度从快到慢
  progressTimer.value = setInterval(() => {
    if (progress.value < 70) {
      // 初期进度较快
      progress.value += Math.floor(Math.random() * 3) + 1
    } else if (progress.value < 90) {
      // 中期进度变慢
      if (Math.random() > 0.4) { // 60%概率增加进度
        progress.value += 1
      }
    } else if (progress.value < 99) {
      // 后期进度很慢
      if (Math.random() > 0.7) { // 30%概率增加进度
        progress.value += 1
      }
    } else if (progress.value === 99) {
      // 到99%时停顿
      clearInterval(progressTimer.value)

      // 最后阶段卡住一段时间，然后跳到100%
      setTimeout(() => {
        progress.value = 100

        // 在100%时额外等待
        setTimeout(() => {
          isDetecting.value = false
          isWaitingResult.value = false
          showResult.value = true

          // 模拟结果数据
          similarity.value = Math.floor(Math.random() * 21) + 10
          detectionTime.value = new Date().toLocaleString()

          if (activeTab.value === 'file') {
            wordCount.value = fileWordCount.value
          } else {
            wordCount.value = inputText.value.length
          }
        }, 1500) // 100%后再等待1.5秒
      }, 2000) // 99%时等待2秒
    }
  }, 180) // 放慢整体速度，间隔从100ms增加到180ms
}

const resetDetection = () => {
  showResult.value = false
  fileList.value = []
  fileWordCount.value = 0
  inputText.value = ''
  activeTab.value = 'file'
}

// 清理
onMounted(() => {
  return () => {
    if (progressTimer.value) {
      clearInterval(progressTimer.value)
    }
  }
})
</script>

<style scoped>
.detect-container {
  max-width: 1200px;
  margin: 40px auto;
  padding: 0 20px;
}

/* 添加内容容器，用于横向排列卡片和图片 */
.detect-content-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 30px;
  margin-bottom: 30px;
}

.detect-card {
  flex: 1;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 右侧查重图片样式 - 简洁版本 */
.detect-image {
  width: 380px;
  height: auto;
  transition: transform 0.3s ease;
  margin-top: -30px;
}

.detect-image:hover {
  transform: translateY(-5px);
}

.detect-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 限时免费通知样式 - 蓝色主题 */
.promo-banner {
  background: linear-gradient(135deg, rgba(0, 255, 225, 0.7), rgba(28, 105, 189, 0.75));
  color: #212121;
  padding: 16px 25px;
  border-radius: 12px;
  margin-bottom: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6px 16px rgba(28, 105, 189, 0.3);
  position: relative;
  overflow: hidden;
}

.promo-banner::before {
  content: "";
  position: absolute;
  top: -30px;
  right: -30px;
  width: 150px;
  height: 150px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  z-index: 0;
}

.promo-banner .el-icon {
  font-size: 26px;
  margin-right: 15px;
  animation: pulse 2s infinite;
  color: #1a237e; /* 深蓝色图标 */
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  /* 更明显的脉动效果 */
  100% {
    transform: scale(1);
  }
}

.promo-text {
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 0.5px;
  flex-grow: 1;
  text-align: center;
}

.highlight-text {
  color: #1a237e; /* 深蓝色高亮 */
  font-size: 22px;
  font-weight: 700;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.4);
  margin: 0 5px;
}

.detect-header {
  text-align: center;
  margin-bottom: 20px;
  color: #31a3bc;
}

.detect-header h2 {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 4px;
}

.subtitle {
  color: #909399;
  margin-top: 5px;
}

.detect-tabs {
  margin-top: 20px;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 修改上传区域样式 */
.upload-box {
  width: 100%;
  margin-bottom: 20px;
}

/* 修改拖拽区域背景为蓝色 */
.upload-box :deep(.el-upload-dragger) {
  background: linear-gradient(135deg, #e6f1ff, #d0e4ff);
  border: 2px dashed #3b6c97;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.upload-box :deep(.el-upload-dragger:hover) {
  background: linear-gradient(135deg, #d0e4ff, #bbd8ff);
  border-color: #409EFF;
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(64, 158, 255, 0.2);
}

.upload-box :deep(.el-upload-dragger.is-dragover) {
  background: rgba(64, 158, 255, 0.1);
  border-color: #409EFF;
}

.upload-icon {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 12px;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.upload-text {
  font-size: 16px;
  color: #475669;
  margin-bottom: 4px;
}

.upload-text em {
  color: #409EFF;
  font-style: normal;
  font-weight: 600;
  text-decoration: underline;
}

.upload-tip {
  font-size: 14px;
  color: #8492a6;
  margin-top: 8px;
}

.word-count-requirement {
  color: #f56c6c;
  font-weight: 500;
}

.uploaded-files {
  width: 100%;
  padding: 0 20px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 14px 16px;
  background: #eef5ff;
  border-radius: 8px;
  margin: 10px 0;
  color: #475669;
  border-left: 4px solid #409EFF;
  transition: all 0.3s ease;
}

.file-item:hover {
  background: #e0efff;
  transform: translateX(2px);
}

.file-name {
  flex: 1;
  margin: 0 12px;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
}

.file-word-count {
  margin-left: 10px;
  color: #409EFF;
  font-weight: 500;
  font-size: 13px;
  background: rgba(64, 158, 255, 0.1);
  padding: 2px 8px;
  border-radius: 10px;
}

.text-input {
  border-radius: 8px;
  margin-bottom: 10px;
}

.text-input :deep(.el-textarea__inner) {
  border: 2px solid #d0e4ff;
  border-radius: 8px;
  transition: all 0.3s;
  padding: 12px;
}

.text-input :deep(.el-textarea__inner:focus) {
  border-color: #409EFF;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

.text-counter {
  text-align: right;
  color: #909399;
  font-size: 13px;
  margin-top: 5px;
  padding-right: 10px;
}

.text-counter-error {
  color: #f56c6c;
}

.text-counter-error span {
  font-weight: 500;
}

.action-area {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  margin-bottom: 10px;
}

.submit-btn {
  width: 250px;
  height: 48px;
  border-radius: 24px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  transition: all 0.3s ease;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(64, 158, 255, 0.2);
}

/* 进度条样式 */
.progress-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.progress-icon {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 20px;
}

.spinning {
  animation: spin 1.5s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.progress-bar {
  width: 100%;
  margin: 20px 0;
}

.progress-info {
  color: #909399;
  font-size: 14px;
}

/* 结果样式 */
.result-content {
  padding: 20px 0;
}

.result-header {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.similarity-display {
  display: flex;
  align-items: center;
}

.similarity-circle {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transition: transform 0.3s ease;
}

.similarity-circle:hover {
  transform: scale(1.05);
}

.level-low {
  background-color: #67C23A;
  color: white;
}

.level-medium {
  background-color: #E6A23C;
  color: white;
}

.level-high {
  background-color: #F56C6C;
  color: white;
}

.similarity-value {
  font-size: 32px;
  font-weight: bold;
}

.similarity-text {
  display: flex;
  flex-direction: column;
}

.similarity-label {
  font-size: 18px;
  color: #606266;
  margin-bottom: 5px;
}

.similarity-level {
  font-size: 20px;
  font-weight: bold;
}

.result-details {
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
}

.detail-item .label {
  color: #909399;
}

.detail-item .value {
  font-weight: 500;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .detect-content-wrapper {
    flex-direction: column;
    align-items: center;
  }

  .detect-image {
    width: 100%;
    max-width: 480px;
    margin-top: 30px;
  }
}

@media (max-width: 768px) {
  .detect-container {
    padding: 0 15px;
  }

  .promo-banner {
    padding: 14px 18px;
  }

  .promo-text {
    font-size: 16px;
  }

  .highlight-text {
    font-size: 20px;
  }

  .promo-banner .el-icon {
    font-size: 22px;
  }

  .upload-icon {
    font-size: 40px;
  }

  .submit-btn {
    width: 100%;
  }

  .similarity-circle {
    width: 100px;
    height: 100px;
  }

  .similarity-value {
    font-size: 28px;
  }
}

@media (max-width: 480px) {
  .promo-banner {
    padding: 12px 15px;
  }

  .promo-text {
    font-size: 15px;
  }

  .highlight-text {
    font-size: 18px;
  }
}
</style>